package cn.zsb.zsb.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author oldliu
 * @since 1.0
 */
@Component("timeInterceptor")
public class TimeInterceptor extends HandlerInterceptorAdapter {

    @Override//handler请求之前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       long start=System.nanoTime();
       request.setAttribute("start",start);
        if(request.getParameter("USER_LOGIN")==null){
           request.getRequestDispatcher("/error.jsp").forward(request,response);
           return false;
       }
        //一般，要给他一个渲染结果页面
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println("Qingqiu:"+request.getServletPath()+",处理器："+handler+"\n返回结果是："+modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        long start=(Long)request.getAttribute("start");
        long end=System.nanoTime();

        System.out.println("本次请求:"+request.getServletPath()+"耗时"+(end-start)+"纳秒");
    }
}
